<?php

namespace app\model\v1\recovery;

use app\common\Ip2Region;
use app\model\user\User;
use app\model\v1\recruit\RecruitPersonageAuthentication;
use constants\ProductConstants;
use crmeb\traits\ModelTrait;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\Model;

class RecoveryProductShop extends Model
{
    use ModelTrait;

    protected $updateTime = false;
    protected $createTime = false;

    protected $hidden = [
   //     'create_time','update_time','delete_time'
    ];



    const SHOP_TYPE = 1;  //商铺
    const PRODUCT_TYPE = 2;  //办公转租

    //protected $type = [
    //    'images' => 'json'
    //];

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid');
    }


    public function category()
    {
        return $this->hasOne(RecoveryProductCategory::class, 'id', 'category_id');
    }

    public function collect()
    {
        return $this->hasOne(RecoveryUserRelation::class, 'id', 'product_id');
    }

    public function searchCategoryIdAttr($query, $value)
    {
        $query->where('category_id', $value);
    }

    public function searchProductNameAttr($query, $value)
    {
        $query->where('product_name', 'like', '%' . $value . '%');
    }

    public function searchOnSaleAttr($query, $value)
    {
        $query->where('on_sale', $value);
    }


    /**
     * 首页 - 闲置发布 - 发布店铺
     * @param $param
     * @return int|string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function addProductShop($param = [])
    {
        // 校验是否重复发布店铺
        if($param["type"] == 1){
            $find = self::where(function ($query) use ($param){
                    $query->whereNull("delete_time");
                    $query->where(["uid"=>$param["user_id"], "category_id"=>$param["category_id"]]);
                    $query->where("status", '<>', 3);
                })
                ->find();
            if(!empty($find))  throw new Exception("不能重复添加店铺！");
        }

        $reg_find = RecruitPersonageAuthentication::where(["u_id"=>$param["user_id"]])->whereNull("delete_at")->find();
        if(empty($reg_find))  throw new Exception("请先实名认证！");
        if(!empty($find["status"])){
            if($find["status"] == 1) {
                throw new Exception("审核中，请实名审核通过后再发布！");
            }else if($find["status"] == 3) {
                throw new Exception("审核未通过，请实名认证审核！");
            }
        }

        $add = self::formatProductShopAdd($param);
        return self::insert($add);
    }


    public static function formatProductShopAdd($param = [])
    {
        $add = [
            'uid'               => $param['user_id'],  //用户id
            'category_id'       => $param['category_id'] ?? '',  //分类id
            'img'               => $param['img'] ?? '',  //资料图片
            'title'             => $param['title'] ?? '',  //标题
            'area'              => $param['area'] ?? '',  //区域
            'area_id'           => $param['area_id'] ?? '',  //省份id
            'city_id'           => $param['city_id'] ?? '',  //市id
            'origin_id'         => $param['origin_id'] ?? '',  //区域id
            'address'           => $param['address'] ?? '',  //店铺地址
            'number'            => $param['number'] ?? '',  //楼层房号
            'shop_type'         => $param['shop_type'] ?? NULL,  //店铺类型
            'insdustry'         => $param['insdustry'] ?? NULL,  //经营行业   写字楼装修
            'measure'           => $param['measure'] ?? '',  //面积
            'rent'              => $param['rent'] ?? '',  //租金
            'lease_term'        => $param['lease_term'] ?? '',  //剩余租期    免租期
            'transfer_cost'     => $param['transfer_cost'] ?? NULL,  //转让费   起租期
            'desc'              => $param['desc'] ?? '',  //详情介绍
            'plege'             => $param['plege'] ?? '',  //   押付方式  押
            'symbol'            => $param['symbol'] ?? '',  //   押付方式  付
            'use'               => $param['use'] ?? '',  //   使用率
            'tag'               => $param['tag'] ?? '',  //标签
            'is_agree'          => $param['is_agree'] ?? '',  //是否已阅读并同意协议 1是 2否
            'type'              => $param['type'] ?? '',  //1店铺 2办公转租
            'logo'              => $param['logo'] ?? '',  // 商铺logo
            'info'              => $param['info'] ?? '',  // 商铺信息
            'shop_user_img'     => $param['shop_user_img'] ?? '',  //商铺用户身份证图片
            'is_shop'           => $param['is_shop'] ?? '',
            'create_time'       => time(),   //创建时间
        ];
        return $add;
    }


    /**
     * 我发布的-商品编辑
     * @param $param
     * @return int|string
     * @throws Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function updateProductShop($param = [])
    {
        $update = self::formatProductShopupdate($param);
        return Db::name("recovery_product_shop")->where("id", $param["id"])->update($update);
    }


    public static function formatProductShopupdate($param = [])
    {
        $update["update_time"] = time();   //更新时间
        if(!empty($param['user_id']))           $update["uid"] = $param['user_id']; //用户id
        if(!empty($param['category_id']))       $update["category_id"] = $param['category_id']; //分类id
        if(!empty($param['img']))               $update["img"] = $param['img']; //资料图片
        if(!empty($param['title']))             $update["title"] = $param['title']; //标题
        if(!empty($param['area']))              $update["area"] = $param['area']; //区域
        if(!empty($param['area_id']))           $update["area_id"] = $param['area_id']; //区域
        if(!empty($param['city_id']))           $update["city_id"] = $param['city_id']; //区域
        if(!empty($param['origin_id']))         $update["origin_id"] = $param['origin_id']; //区域
        if(!empty($param['address']))           $update["address"] = $param['address']; //店铺地址
        if(!empty($param['shop_type']))         $update["shop_type"] = $param['shop_type']; //店铺类型
        if(!empty($param['insdustry']))         $update["insdustry"] = $param['insdustry']; //经营行业   写字楼装修
        if(!empty($param['measure']))           $update["measure"] = $param['measure']; //面积
        if(!empty($param['rent']))              $update["rent"] = $param['rent']; //租金
        if(!empty($param['lease_term']))        $update["lease_term"] = $param['lease_term']; //剩余租期    免租期
        if(!empty($param['transfer_cost']))     $update["transfer_cost"] = $param['transfer_cost']; //转让费   起租期
        if(!empty($param['desc']))              $update["desc"] = $param['desc']; //详情介绍
        if(!empty($param['plege']))             $update["plege"] = $param['plege']; //押付方式  押
        if(!empty($param['symbol']))            $update["symbol"] = $param['symbol']; //押付方式  付
        if(!empty($param['use']))               $update["use"] = $param['use']; //使用率
        if(!empty($param['tag']))               $update["tag"] = $param['tag']; //标签
        if(!empty($param['logo']))              $update["logo"] = $param['logo']; //logo
        if(!empty($param['info']))              $update["info"] = $param['info']; //商铺信息
        if(!empty($param['shop_user_img']))     $update["shop_user_img"] = $param['shop_user_img']; //店铺用户身份证图片
        if(!empty($param['is_agree']))          $update["is_agree"] = $param['is_agree']; //是否已阅读并同意协议 1是 2否
        if(!empty($param['reset']))             $update["status"] = 1;

        return $update;
    }


    /**
     * 用户举报
     * @param $param
     * @return int|string
     */
    public static function createReport($param = [])
    {
        $reg_find = RecruitPersonageAuthentication::where(["u_id"=>$param["user_id"]])->whereNull("delete_at")->find();
        if(empty($reg_find))  throw new Exception("请先实名认证！");
        if(!empty($find["status"])){
            if($find["status"] == 1) {
                throw new Exception("审核中，请实名审核通过后再发布！");
            }else if($find["status"] == 3) {
                throw new Exception("审核未通过，请实名认证审核！");
            }
        }

        //接收用户参数，将数据提交到数据库
        $add = [
            'uid'       => $param['user_id'] ?? '',  //用户id
            'title'     => $param['title'] ?? '',  //标题
            'cate'      => $param['cate'] ?? '',  //举报类型
            'img'       => $param['img'] ?? '',  //图片
            'module'    => $param['module'],
            'reason'    => $param['reason'] ?? '',  //原因描述
            'type'      => $param['type'] ?? '',  //1商家主页举报 2商品详情页举报
            'create_time'=> time(),  // 创建时间
        ];
        return Db::name("recovery_report")->insert($add);
    }



    /**
     * 首页 - 根据店铺闲置分类 - 获取店铺列表
     * @param $params
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getCategoryShopList($params = [])
    {
        //接收用户传参发送过来的参数，从数据库中检索获取数据
        $data["data"] = self::alias("a")
            ->field("a.*, b.cate_name")
            ->join ('recovery_product_category b','a.category_id=b.id','left')
            ->whereNull("a.delete_time")
            ->where(function ($query) use ($params){
                $query->where("a.status", 2);
                if(!empty($params["category_id"])) $query->where("a.category_id", $params["category_id"]);  //根据分类id搜索
                if(!empty($params["word"])) $query->where("a.title", 'like', '%'.$params["word"].'%');   //根据关键字搜索
            })
            ->order(['a.id' => 'desc'])
            ->page($params["page"], $params['limit'])
            ->select()->toArray();

        $data["count"] = self::alias("a")
            ->field("a.*, b.cate_name")
            ->join ('recovery_product_category b','a.category_id=b.id','left')
            ->whereNull("a.delete_time")
            ->where(function ($query) use ($params){
                $query->where("a.status", 2);
                if(!empty($params["category_id"])) $query->where("a.category_id", $params["category_id"]);  //根据分类id搜索
                if(!empty($params["word"])) $query->where("a.title", 'like', '%'.$params["word"].'%');   //根据关键字搜索
            })
            ->count();

        if(!empty($data["data"])){
            foreach ($data["data"] as $key => &$val){
                $val["tag_name"] = self::getShopTag($val["tag"]);
                $val["tag_shop_name"] = RecoveryProduct::getUserShopTag($val["uid"]);
                $val["pid_cate_name"] = self::getPidCateName($val["category_id"]);
            }
        }

        return $data;
    }

    public static function getPidCateName($category_id = '')
    {
        if(empty($category_id)) return '';
        $pid = Db::name("recovery_product_category")->where("id", $category_id)->value("pid") ?? 0;
        $pid_cate_name = Db::name("recovery_product_category")->where("id", $pid)->value("cate_name") ?? '';
        return $pid_cate_name;
    }



    /**
     * 获取店铺的标签
     * @param $tag_ids
     * @return array|false|string
     */
    public static function getShopTag($tag_ids = '')
    {
        if(empty($tag_ids)) return '';
        $tag_ids = explode(",", $tag_ids);
        $tag = Db::name("recovery_question_cate")->whereIn("id", $tag_ids)->column("cate_name") ?? [];
        return $tag;
    }


    /**
     * 店铺闲置 - 店铺详情
     * @param int $id
     * @param array $param
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function detail(int $id, array $param = [])
    {
        $where = ['a.id' => $id];

        $item = self::alias("a")
            ->field("a.*, b.cate_name")
            ->join('recovery_product_category b', 'a.category_id=b.id','left')
            ->where($where)
            ->find();
        if (empty($item)) throw new Exception('店铺不存在');

        $item->visit_count += 1;  //添加店铺的浏览量
        $item->save();

        $item = $item->toArray();    // 将object信息转换成数组返回给页面

        $user = User::where("uid", $item["uid"])->field("uid,nickname,phone,avatar")->find() ?? [];
        if(!empty($user)) $user = $user->toArray();
        $item['user'] = $user;

        $item["tag_name"] = self::getShopTag($item["tag"]);
        $item["tag_shop_name"] = RecoveryProduct::getUserShopTag($item["uid"]);

        //店铺下的自由市场的商品  以及办公闲置
        $free_cate_id = RecoveryProductCategory::getCategoryIdByName("自由市场");
        $free_cate_id_arr = RecoveryProductCategory::getChildrenIds($free_cate_id);
        $tition_cate_id = RecoveryProductCategory::getCategoryIdByName("办公闲置");
        $tition_cate_id_arr = RecoveryProductCategory::getChildrenIds($tition_cate_id);
        $ids_arr = array_merge($free_cate_id_arr, $tition_cate_id_arr);
        $cate_id1 = RecoveryProductCategory::getCategoryIdByName("店铺闲置");
        $cate_id_arr1 = RecoveryProductCategory::getChildrenIds($cate_id1);
        $ids_arr = array_merge($ids_arr, $cate_id_arr1);
        $item["product"] = RecoveryProduct::getProductByCateAndUid($ids_arr, $item["uid"]);   //[$free_cate_id,$tition_cate_id]

        //店铺闲置的商品
        $cate_id = RecoveryProductCategory::getCategoryIdByName("店铺闲置");
        $cate_id_arr = RecoveryProductCategory::getChildrenIds($cate_id);
        $item["tition_product"] = RecoveryProduct::getProductByCateAndUid($cate_id_arr, $item["uid"]);

        //店铺转让的数据
        $cate_id = RecoveryProductCategory::getCategoryIdByName("店铺转让");
        $cate_id_arr = RecoveryProductCategory::getChildrenIds($cate_id);
        $item["shop"] = self::getShopByCateAndUid($cate_id_arr, $item["uid"]);

        //卡类转让的数据
        $card_cate_id = RecoveryProductCategory::getCategoryIdByName("卡类转让");
        $card_cate_id_arr = RecoveryProductCategory::getChildrenIds($card_cate_id);
        $item["card"] = RecoveryProduct::getProductByCateAndUid($card_cate_id_arr, $item["uid"]);

        //办公转租
        $cate_id = RecoveryProductCategory::getCategoryIdByName("办公转租");
        $cate_id_arr = RecoveryProductCategory::getChildrenIds($cate_id);
        $item["rent_data"] = self::getShopByCateAndUid($cate_id_arr, $item["uid"]);

        $ip2region = new Ip2Region();
        $ipInfo = $ip2region->btreeSearch($user["ip"] ?? '114.244.11.10');
        $item["ip_city"] = explode("|", $ipInfo["region"]??'')[2] ?? '';

        return $item;
    }





    /**
     * 根据分类id、用户id获取商铺列表
     * @param $cate_id
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getShopByCateAndUid($cate_id='', $uid='')
    {
        $data = self::where(function ($query) use ($uid,$cate_id){
                $query->where("status", 2);
                $query->where("on_sale", 1);
                if(!empty($uid)) $query->where("uid", $uid);
                if(is_array($cate_id)){
                    $query->whereIn("category_id", $cate_id);
                } else{
                    $query->where("category_id", $cate_id);
                }
            })
            ->select()->toArray();

        if(!empty($data)){
            foreach ($data as $key => &$val){
                $val["tag_name"] = self::getShopTag($val["tag"]);
            }
        }

        return $data;
    }


    /**
     * 店铺转让管理列表
     * @param $param
     * @return array
     */
    public static function getProductShopList($param = [])
    {
        $param['page'] =  $param['page'] ?? 1;
        $param['limit'] =  $param['limit'] ?? 10;
        $order = ["a.id"=>"desc"];
        //按照创建时间排序
        if(!empty($param["order_ctime"])){
            if(!empty($param["order_ctime_sc"])){
                $order = ["a.id"=>"desc", "a.create_time"=> $param["order_ctime_sc"]];
            }else{
                //默认按照字段降序排序
                $order = ["a.id"=>"desc", "a.create_time"=>"desc"];
            }
        }

        $data['data'] = self::alias("a")
            ->field ("a.*,b.cate_name,FROM_UNIXTIME(a.create_time) as create_time,c.real_name,c.avatar,c.nickname,c.phone,
            case when a.type=1 then '店铺转让'
            when a.type=2 then '办公转租'
            end as type_text,
            case when a.status=1 then '待审核'
            when a.status=2 then '审核通过'
            when a.status=3 then '审核不通过'
            end as status_text
            ")
            ->join ('recovery_product_category b','a.category_id=b.id','left')
            ->join ('user c','a.uid=c.uid','left')
            ->where(function ($query) use ($param){
                $query->whereNull("a.delete_time");
               // $query->where("a.is_shop", 1);
                if(!empty($param["sys_word"])) $query->where("a.status",  2);
                if(!empty($param["type"])) $query->where("a.type",  $param["type"]);
                if(!empty($param['time'])){    //根据创建日期搜索
                    $wheretime = explode (',',$param['time']);
                    $query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("a.title",'like', '%'.$param["word"].'%');
                if(!empty($param["category_id"])) $query->where("a.category_id", $param["category_id"]);
                if(!empty($param['rent'])){
                    $whereprice = explode (',',$param['rent']);
                    $query->where('a.rent', 'between', [strtotime($whereprice[0]),strtotime($whereprice[1])]);
                }
            })
            ->order($order)
            ->page($param['page'], $param['limit'])
            ->select()->toArray();

        $data['count'] = self::alias("a")
            ->field ("a.*,b.cate_name")
            ->join ('recovery_product_category b','a.category_id=b.id','left')
            ->where(function ($query) use ($param){
                $query->whereNull("a.delete_time");
              //  $query->where("a.is_shop", 1);
                if(!empty($param["sys_word"])) $query->where("a.status",  2);
                if(!empty($param["type"])) $query->where("a.type",  $param["type"]);
                if(!empty($param['time'])){    //根据创建日期搜索
                    $wheretime = explode (',',$param['time']);
                    $query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("a.title",'like', '%'.$param["word"].'%');
                if(!empty($param["category_id"])) $query->where("a.category_id", $param["category_id"]);
                if(!empty($param['rent'])){
                    $whereprice = explode (',',$param['rent']);
                    $query->where('a.rent', 'between', [strtotime($whereprice[0]),strtotime($whereprice[1])]);
                }
            })
            ->count();

        if(!empty($data["data"])){
            foreach ($data["data"] as $key => &$val){
                $val["tag_name"] = self::getShopTag($val["tag"]);
                $val["tag_shop_name"] = RecoveryProduct::getUserShopTag($val["uid"]);
                $val["pid_cate_name"] = self::getPidCateName($val["category_id"]);
            }
        }

        return $data;
    }



    public static function getProductShopDetail($param = [])
    {
        $detail =  self::alias("a")
            ->field ("a.*,b.cate_name,FROM_UNIXTIME(a.create_time) as create_time,
            case when a.type=1 then '店铺转让'
                when a.type=2 then '办公转租'
                end as type_text,
            case when a.status=1 then '待审核'
                when a.status=2 then '审核通过'
                when a.status=3 then '审核不通过'
                end as status_text
            ")
            ->join ('recovery_product_category b','a.category_id=b.id','left')
            ->where("a.id", $param["id"])
            ->find();

        return $detail;
    }


    public static function enableShopStatus($param = [])
    {
        $find = self::where("id", $param['id'])->find();
        if(empty($find)) return -1;

        $update = ['status' => $param["status"]];    //, "on_sale" => $param["status"]-1
        if(!empty($param["audit_desc"])) $update["audit_desc"] = $param["audit_desc"];

        $res = self::where("id", $param['id'])->update($update);

        if($param["status"] == 3){
            event('user.recovery', [$find['uid'], $find['title'], $param["audit_desc"]]);
        }
        return $res;
    }





    /**
     * 店铺转让管理列表 - 启用禁用
     * @param $param
     * @return string
     */
    public static function enableProductShopStatus($param = [])
    {
        $status = self::where("id", $param['id'])->value("on_sale");
        $msg = '';
        if($status == 1){   //1上架 2下架
            $enable = 2;
            $msg = "下架成功";
        }else{
            $enable = 1;
            $msg = "上架成功";
        }
        self::where("id", $param['id'])->update(['on_sale' => $enable]);
        return $msg;
    }




    /**
     * 我的发布 -   2下架     111申请上架
     * @param $param
     * @return int|string
     * @throws Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function enablePublishShop($param = [])
    {
        $on_sale = 3;
        if($param["on_sale"] === 111){
            $on_sale = 0;
        }
        $update = [
            "on_sale" => $on_sale,
            //"is_sale" => 1,
        ];
        if($param["on_sale"] === 111){
            $update["status"] = 1;
        }

        //$find = RecoveryProductQuote::where("product_id", $param["id"])->whereIn("status", [2,3])->find();
        //if(!empty($find)) Throw new Exception('此商品正在交易当中！');

        return Db::name("recovery_product_shop")->where("id", $param["id"])->update($update);
    }



    /**
     * 我的发布 - 店铺删除
     * @param $param
     * @return int|string
     * @throws Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function delPublishShop($param = [])
    {
        return Db::name("recovery_product_shop")->where("id", $param["id"])->update(["delete_time"=>time()]);
    }



}